/*
 * Copyright 2008-2023 dexian.vip. All rights reserved.
 * Support: http://www.dexian.vip
 * License: http://www.dexian.vip/license
 */

package vip.dexian.admin.security.handler;

import vip.dexian.admin.security.config.SecurityConfig;
import vip.dexian.admin.security.exception.CaptchaInvalidException;
import vip.dexian.common.Message;
import vip.dexian.common.utils.WebUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 认证失败处理
 *
 * @author 挺好的 2023年06月06日 15:25
 */
@Component ("simpleAuthenticationFailureHandler")
@Slf4j
public class SimpleAuthenticationFailureHandler implements AuthenticationFailureHandler {

    /***
     * 登录失败的操作
     * @param request
     * {@link jakarta.servlet.http.HttpServletRequest}
     * @param response
     * {@link jakarta.servlet.http.HttpServletResponse}
     * @param exception
     * 异常信息 。{@link org.springframework.security.core.AuthenticationException}
     * @throws java.io.IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationFailure (HttpServletRequest request, HttpServletResponse response,
            AuthenticationException exception) throws IOException, ServletException {

        log.debug("authentication failure：", exception);

        response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());

        // 如果不是ajax请求
        if (!WebUtils.isAjaxRequest(request)) {
            response.sendRedirect(SecurityConfig.LOGIN);
            return;
        }

        String message;
        if (exception instanceof UsernameNotFoundException || exception instanceof BadCredentialsException) {
            message = "用户名或密码输入错误";
        } else if (exception instanceof DisabledException) {
            message = "账户被禁用，请联系管理员!";
        } else if (exception instanceof LockedException) {
            message = "账户被锁定，请稍后重试!";
        } else if (exception instanceof CaptchaInvalidException) {
            message = "验证码不正确";
        } else {
            message = "登录失败";
        }

        WebUtils.responseMessage(response, Message.warn(message));
    }
}
